// Fill out your copyright notice in the Description page of Project Settings.


#include "UserWidget/WidgetComponent/TimerWidget.h"
#include "Components/TextBlock.h"
#include "Component/MissionComponent.h"
#include "Libraries/MissionSystemFL.h"
#include "Libraries/CommonLibrary.h"

void UTimerWidget::NativeConstruct()
{
	Super::NativeConstruct();
	InSeconds = TimeInfo.TimeInSeconds;
	TimerText->SetText(SecondsToText(InSeconds));
	FTimerDelegate RespawnDelegate = FTimerDelegate::CreateUObject(this, &UTimerWidget::TimeCounter);
	GetWorld()->GetTimerManager().SetTimer(TimerHandle, RespawnDelegate, 1.f, true);
	PlayAnimation(UCommonLibrary::GetAnimInstance(GetClass(), FText::FromString("SlideIn")), 0.f, 1, EUMGSequencePlayMode::Reverse);
}

void UTimerWidget::NativeDestruct()
{
	Super::NativeDestruct();
	GetWorld()->GetTimerManager().ClearTimer(TimerHandle);
	PlayAnimation(UCommonLibrary::GetAnimInstance(GetClass(), FText::FromString("SlideIn")), 0.f, 1, EUMGSequencePlayMode::Reverse);
}

void UTimerWidget::RequestDestruct()
{
	UWidgetAnimation* SlideIn = UCommonLibrary::GetAnimInstance(GetClass(), FText::FromString("SlideIn"));
	PlayAnimation(SlideIn, 0.f, 1, EUMGSequencePlayMode::Forward);
	if (DelayHandle.IsValid()) {
		return;
	}
	else {
		FTimerDelegate RespawnDelegate = FTimerDelegate::CreateUObject(this, &UTimerWidget::DelayLater);
		GetWorld()->GetTimerManager().SetTimer(DelayHandle, RespawnDelegate, SlideIn->GetEndTime() + 0.1, false);
	}
}

void UTimerWidget::ConstructWidget(const FTimerInfo& TargetInfo, float LWarningTime)
{
	TimeInfo = TargetInfo;
	WarningTime = LWarningTime;
}

FText UTimerWidget::SecondsToText(float Seconds)
{
	FString StringA, StringB, mm, ss;
	StringB = FString::FromInt(FMath::FloorToInt(Seconds / 60.f));
	StringA = FString("0").Append(StringB);
	if (FMath::FloorToInt(Seconds / 60.f) > 9) {
		mm = StringB;
	}
	else {
		mm = StringA;
	}
	StringB = FString::FromInt(FMath::FloorToInt(FMath::Fmod(Seconds, 60.f)));
	StringA = FString("0").Append(StringB);
	if (FMath::FloorToInt(FMath::Fmod(Seconds, 60.f)) > 9) {
		ss = StringB;
	}
	else {
		ss = StringA;
	}
	mm.Append(FString(":"));
	mm.Append(ss);
	FText Result= FText::FromString(mm);
	return Result;
}

void UTimerWidget::TimeCounter()
{
	InSeconds = FMath::Clamp(InSeconds - 1.f, 0.f, InSeconds);
	TimerText->SetText(SecondsToText(InSeconds));
	if (InSeconds == 0.f) {
		GetWorld()->GetTimerManager().ClearTimer(TimerHandle);
		UMissionSystemFL::GetMissionComponent()->OnCountDownTimerFinished();
	}
	else if(InSeconds<= WarningTime){
		PlayAnimation(UCommonLibrary::GetAnimInstance(GetClass(), FText::FromString("AnimateSeconds")), 0.f, 0, EUMGSequencePlayMode::PingPong);
	}
}

void UTimerWidget::DelayLater(){
	RemoveFromParent();
	GetWorld()->GetTimerManager().ClearTimer(DelayHandle);
}
